此时
相当于 super()
。(在子类的this上运行父类的构造函数)父类构造函数.call(this)
class A {
name = 'A'
constructor() {
console.log(`My name is ${this.name}`)
}
}
class B extends A {
name = 'B'
}
const b = new B() // My name is A
看看方法会不会出现同样的问题
class A {
name = 'A'
constructor() {
console.log(`My name is ${this.getX()}`)
}
getX() {
return 'xa'
}
}
class B extends A {
name = 'B'
getX() {
return 'xb'
}
}
const b = new B() // My name is xb
由上可见方法是没有问题的
函数只能用在子类的构造函数之中,用在其他地方就会报错super()
指向父类的原型对象;调用父类原型对象的方法时,方法内部的this指向子类实例
对某个属性赋值时,直接指向子类实例
有趣的赋值
class A {
constructor() {
this.x = 1
}
}
class B extends A {
constructor() {
super()
this.x = 2
super.x = 3
console.log(super.x) // undefined
console.log(this.x) // 3
}
}
const b = new B()
class A {
constructor() {
this.x = 1
}
static print() {
console.log(this.x)
}
}
class B extends A {
constructor() {
super()
this.x = 2
}
static m() {
super.print()
}
}
B.x = 3
B.m() // 3
const obj = {
toString() {
return `MyObject: ${super.toString()}`
}
}
obj.toString() // MyObject: [object Object]